<?php

namespace App\Jobs;

use Exception;
use App\Constant\QueueKey;
use App\Facades\CommonPlatformRequestFacade;
use App\Models\UserAuthSpiderTransLog;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class RiskReptileJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 300; //秒数

    /**
     * @var UserAuthSpiderTransLog
     */
    protected $model;

    /**
     * RiskReptileJob constructor.
     * @param UserAuthSpiderTransLog $model
     */
    public function __construct(UserAuthSpiderTransLog $model)
    {
        $this->onQueue(QueueKey::QUEUE_RISK_REPTILE_STATUS);
        $this->model = $model;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
//        $model = $this->model;
//        $status = UserAuthSpiderTransLog::getStatusByRiskInfo($model->trade_no,$model,UserAuthSpiderTransLog::TYPE_CARRIER);
//        if ($status != UserAuthSpiderTransLog::STATUS_INIT) {
//            $model->status = UserAuthSpiderTransLog::STATUS_SUCCESS;
//            \Log::debug('当前模型 '.json_encode($this->model->toArray(),JSON_UNESCAPED_UNICODE));
//            \Log::debug('当前爬虫tradeNo为 '.$this->model->trade_no.'状态为'.$this->model->status.'变更为'.$status);
////            $model->save();
//        }
//
//        if (UserAuthSpiderTransLog::STATUS_FAILED == $status) {
//            //失败
//            Log::debug('risk_reptile_job', ['loan_request_id' => $model->loan_request_id]);
//            UserAuthSpiderTransLog::handleByStatus($model->loan_request_id);
//        }

        $status = UserAuthSpiderTransLog::getStatusByRiskInfo($this->model->trade_no, $this->model, UserAuthSpiderTransLog::TYPE_CARRIER);
        if ($status != UserAuthSpiderTransLog::STATUS_INIT) {
            \Log::debug('当前爬虫tradeNo为'.$this->model->trade_no.'状态为' . $this->model->status . '变更为' . $status);
            $this->model->status = $status;
            $this->model->save();
        }

        if ($this->model->status == UserAuthSpiderTransLog::STATUS_FAILED) {
            Log::debug('risk_reptile_job', ['loan_request_id' => $this->model->loan_request_id]);
            UserAuthSpiderTransLog::handleByStatus($this->model->loan_request_id);
        }
    }

    /**
     * 要处理的失败任务。
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception){}
}
